﻿using AutoMapper;
using BW.MesProject.Equipment.Domain.Equipment;
using BW.MesProject.Equipment.Infrastructure.Dto.Input.ProjectForm;
using BW.MesProject.Equipment.Infrastructure.Dto.Output.DeviceLedger;
using BW.MesProject.Equipment.Infrastructure.Dto.Output.ProjectFrom;
using BW.MesProject.Equipment.Infrastructure.Dto.Output.ProjectMaintenance;
using BW.MesProject.Equipment.Infrastructure.Equipment;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace BW.MesProject.Equipment.Application.Equipment
{
    /// <summary>
    /// 项目表单服务实现层
    /// </summary>
    public class ProjectFromService : IProjectFromService
    {
        private readonly IBaseRepository<ProjectFromModel> _projectFormRepository;
        private readonly IMapper _mapper;
        private readonly IBaseRepository<ProjectMaintenanceModel> _projectMaintenanceRepository;
        private readonly IBaseRepository<ProjectFormMaintenanceRelation> _projectFormMaintenanceRelationRepository;
        private readonly ISqlSugarClient _sqlSugarClient;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ProjectFormRepository"></param>
        /// <param name="mapper"></param>
        /// <param name="ProjectMaintenanceRepository"></param>
        public ProjectFromService(IBaseRepository<ProjectFromModel> ProjectFormRepository, IMapper mapper, IBaseRepository<ProjectMaintenanceModel> ProjectMaintenanceRepository ,IBaseRepository<ProjectFormMaintenanceRelation> projectFormMaintenanceRelationRepository,ISqlSugarClient sqlSugarClient)
        {
            _projectFormRepository = ProjectFormRepository;
            _mapper = mapper;
            _projectMaintenanceRepository = ProjectMaintenanceRepository;
            _projectFormMaintenanceRelationRepository = projectFormMaintenanceRelationRepository;
            _sqlSugarClient = sqlSugarClient;
        }

        /// <summary>
        /// 获取项目维护数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ApiResult<List<ProjectMaintenanceModel>> GetProjectMaintenanceValue()
        {
            var projectMaintenance = _projectMaintenanceRepository.GetAll().Where(x => x.IsDeleted == false);

            if(projectMaintenance==null)
            {
                return new ApiResult<List<ProjectMaintenanceModel>>
                {
                    Code=ApiEnums.Error,
                    Message="项目维护数据不存在"
                };
            }
            return new ApiResult<List<ProjectMaintenanceModel>>
            {
                Code = ApiEnums.Success,
                Data = projectMaintenance.ToList(),
                Message = "获取项目维护数据成功",
            };

        }

        /// <summary>
        /// 新增项目表单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ApiResult<int> AddProjectForm(AddProjectFormInput input)
        {
            // 添加事务处理
            var db = _projectFormRepository.GetAll().Context;  // 获取SqlSugarClient
            try
            {
                db.Ado.BeginTran();  // 使用Ado对象开启事务

                // 映射基本信息
                var data = _mapper.Map<ProjectFromModel>(input);
                data.Id = YitIdHelper.NextId();

                // 判断项目维护名称是否已存在，避免重复
                var isExist = _projectFormRepository.GetValue(x => x.ProjectName == data.ProjectName);
                if (isExist != null)
                {
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Error,
                        Message = "项目表单名称已存在"
                    };
                }

                // 添加项目表单
                var res = _projectFormRepository.Add(data);

                // 添加项目表单与项目维护的关联关系
                if (input.ProjectMaintenanceIds != null && input.ProjectMaintenanceIds.Count > 0)
                {
                    var relationList = new List<ProjectFormMaintenanceRelation>();

                    foreach (var maintenanceId in input.ProjectMaintenanceIds)
                    {
                        // 验证项目维护ID是否存在
                        var maintenance = _projectMaintenanceRepository.GetValue(x => x.Id == maintenanceId && !x.IsDeleted);
                        if (maintenance == null)
                        {
                            continue; // 跳过不存在的项目维护ID
                        }

                        // 创建关联记录
                        relationList.Add(new ProjectFormMaintenanceRelation
                        {
                            Id = YitIdHelper.NextId(),
                            ProjectFormId = data.Id,
                            ProjectMaintenanceId = maintenanceId,
                            CreatedBy = data.CreatedBy,
                            CreatedTime = DateTime.Now
                        });
                    }

                    // 批量添加关联记录
                    if (relationList.Count > 0)
                    {
                        foreach (var relation in relationList)
                        {
                            _projectFormMaintenanceRelationRepository.Add(relation);
                        }
                    }
                }

                // 提交事务
                db.Ado.CommitTran();

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Data = res,
                    Message = "项目表单添加成功"
                };
            }
            catch (Exception ex)
            {
                // 回滚事务
                db.Ado.RollbackTran();

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Error,
                    Message = $"添加项目表单失败：{ex.Message}"
                };
            }
        }

        /// <summary>
        /// 获取项目表单列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ApiPaging<ProjectFromOutput> GetProjectFormList(ProjectFormQueryInput input)
        {
            #region 【修改点】注释掉原有代码，使用SqlSugar实现分页功能
            //// 获取未删除的项目表单信息并进行过滤，最后按分页返回结果
            //var projectFormList = _projectFormRepository.GetAll().Where(x => !x.IsDeleted);

            //// 根据条件进行过滤
            //if (!string.IsNullOrEmpty(input.ProjectName))
            //{
            //    projectFormList = projectFormList.Where(x => x.ProjectName.Contains(input.ProjectName));
            //}

            //if (input.ProjectType != null)
            //{
            //    projectFormList = projectFormList.Where(x => x.ProjectType == input.ProjectType);
            //}

            //// 左连接项目维护模型，并选择需要的输出字段
            //var linq = projectFormList.LeftJoin<ProjectMaintenanceModel>((a, b) => a.ProjectMaintenanceId == b.Id && !b.IsDeleted).Select((a, b) => new ProjectFromOutput
            //{
            //    Id = a.Id,
            //    ProjectName = a.ProjectName,
            //    ProjectType = a.ProjectType,
            //    ProjectDescription = a.ProjectDescription,
            //    CreatedBy = a.CreatedBy,
            //    CreatedTime = a.CreatedTime,
            //    UpdatedBy = a.UpdatedBy,
            //    UpdatedTime = a.UpdatedTime,
            //    ProjectMaintenanceId = b.Id,
            //    ProjectMaintenanceName = b.ProjectMaintenanceName,

            //});

            //// 对结果进行排序、分页，并转换为列表
            //var query = linq.OrderByDescending(a => a.Id).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList();

            //// 返回分页结果
            //return new ApiPaging<ProjectFromOutput>
            //{
            //    Code = ApiEnums.Success,
            //    PageData = query,
            //    TotalCount = query.Count(),
            //    Message = "获取项目表单列表成功"
            //};
            #endregion

            // 获取未删除的项目表单信息并进行过滤
            var projectFormList = _projectFormRepository.GetAll().Where(x => !x.IsDeleted);

            // 根据条件进行过滤
            if (!string.IsNullOrEmpty(input.ProjectName))
            {
                projectFormList = projectFormList.Where(x => x.ProjectName.Contains(input.ProjectName));
            }

            if (input.ProjectType != null)
            {
                projectFormList = projectFormList.Where(x => x.ProjectType == input.ProjectType);
            }

            // 获取总记录数
            var totalCount = projectFormList.Count();

            // 获取项目表单列表
            var projectForms = projectFormList.OrderByDescending(a => a.Id)
                .Skip((input.PageIndex - 1) * input.PageSize)
                .Take(input.PageSize)
                .ToList();

            // 如果没有数据，直接返回空列表
            if (projectForms.Count == 0)
            {
                return new ApiPaging<ProjectFromOutput>
                {
                    Code = ApiEnums.Success,
                    PageData = new List<ProjectFromOutput>(),
                    TotalCount = 0,
                    Message = "获取项目表单列表成功，但没有数据"
                };
            }

            // 获取项目表单与项目维护的关联关系
            var projectFormIds = projectForms.Select(x => x.Id).ToList();
            var relations = _projectFormMaintenanceRelationRepository.GetAll()
                .Where(x => projectFormIds.Contains(x.ProjectFormId) && !x.IsDeleted)
                .ToList();

            // 如果没有关联关系，直接映射项目表单数据并返回
            if (relations.Count == 0)
            {
                var resultWithoutRelations = projectForms.Select(form => {
                    var output = _mapper.Map<ProjectFromOutput>(form);
                    //output.ProjectMaintenances = new List<ProjectMaintenanceOutput>();
                    output.ProjectMaintenanceNames = ""; // 【修改点1】添加空的项目维护名称字符串
                    return output;
                }).ToList();

                return new ApiPaging<ProjectFromOutput>
                {
                    Code = ApiEnums.Success,
                    PageData = resultWithoutRelations,
                    TotalCount = totalCount,
                    Message = "获取项目表单列表成功"
                };
            }

            // 获取相关的项目维护信息
            var maintenanceIds = relations.Select(x => x.ProjectMaintenanceId).Distinct().ToList();
            var maintenances = _projectMaintenanceRepository.GetAll()
                .Where(x => maintenanceIds.Contains(x.Id) && !x.IsDeleted)
                .ToList();

            // 构建输出结果
            var result = new List<ProjectFromOutput>();
            foreach (var form in projectForms)
            {
                var output = _mapper.Map<ProjectFromOutput>(form);

                // 获取该表单关联的所有项目维护
                var formRelations = relations.Where(x => x.ProjectFormId == form.Id).ToList();
                var formMaintenances = new List<ProjectMaintenanceOutput>();
                var maintenanceNames = new List<string>(); // 【修改点2】创建一个列表用于存储项目维护名称

                foreach (var relation in formRelations)
                {
                    var maintenance = maintenances.FirstOrDefault(x => x.Id == relation.ProjectMaintenanceId);
                    if (maintenance != null)
                    {
                        var maintenanceOutput = _mapper.Map<ProjectMaintenanceOutput>(maintenance);
                        //maintenanceOutput.CheckoutWayText = GetCheckoutWayText(maintenance.CheckoutWay);
                        formMaintenances.Add(maintenanceOutput);

                        // 【修改点3】添加项目维护名称到列表
                        maintenanceNames.Add(maintenance.ProjectMaintenanceName);
                    }
                }
                //output.ProjectMaintenances = formMaintenances;

                // 【修改点4】将项目维护名称列表合并为逗号分隔的字符串
                output.ProjectMaintenanceNames = string.Join("、", maintenanceNames);

                result.Add(output);
            }

            // 返回分页结果
            return new ApiPaging<ProjectFromOutput>
            {
                Code = ApiEnums.Success,
                PageData = result,
                TotalCount = totalCount,
                Message = "获取项目表单列表成功"
            };
        }

        /// <summary>
        /// 根据id获取项目表单数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ApiResult<ProjectFromOutput> GetProjectFormValue(long id)
        {
            // 获取项目表单基本信息
            var projectForm = _projectFormRepository.GetValue(x => x.Id == id && !x.IsDeleted);

            if (projectForm == null)
            {
                return new ApiResult<ProjectFromOutput>
                {
                    Code = ApiEnums.Error,
                    Message = "项目表单不存在或已删除"
                };
            }

            // 映射基本信息
            var output = _mapper.Map<ProjectFromOutput>(projectForm);

            // 获取关联的项目维护信息
            var relations = _projectFormMaintenanceRelationRepository.GetAll()
                .Where(x => x.ProjectFormId == id && !x.IsDeleted)
                .ToList();

            var maintenanceIds = relations.Select(x => x.ProjectMaintenanceId).ToList();

            // 项目维护对象列表
            var formMaintenances = new List<ProjectMaintenanceOutput>();
            // 项目维护名称列表
            var maintenanceNames = new List<string>();

            if (maintenanceIds.Any())
            {
                var maintenanceModels = _projectMaintenanceRepository.GetAll()
                    .Where(x => maintenanceIds.Contains(x.Id) && !x.IsDeleted)
                    .ToList();

                foreach (var maintenance in maintenanceModels)
                {
                    var maintenanceOutput = _mapper.Map<ProjectMaintenanceOutput>(maintenance);
                    // 设置检验方式文本
                    // maintenanceOutput.CheckoutWayText = GetCheckoutWayText(maintenance.CheckoutWay);
                    formMaintenances.Add(maintenanceOutput);

                    // 添加项目维护名称到列表
                    maintenanceNames.Add(maintenance.ProjectMaintenanceName);
                }
            }

            // 设置项目维护对象列表
            output.ProjectMaintenances = formMaintenances;
            // 设置项目维护名称字符串（用顿号分隔）
            output.ProjectMaintenanceNames = string.Join("、", maintenanceNames);

            // 设置项目维护ID列表（用于编辑表单时回显）
            output.ProjectMaintenanceIds = maintenanceIds;

            return new ApiResult<ProjectFromOutput>
            {
                Code = ApiEnums.Success,
                Data = output,
                Message = "获取项目表单数据成功",
            };
        }

        /// <summary>
        /// 更新项目表单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateProjectForm(UpdateProjectFormInput input)
        {
            // 添加事务处理
            var db = _projectFormRepository.GetAll().Context;
            try
            {
                db.Ado.BeginTran();

                var projectFormModel = _projectFormRepository.GetValue(x => x.Id == input.Id && !x.IsDeleted);

                if (projectFormModel == null)
                {
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Error,
                        Message = "项目表单不存在或已删除"
                    };
                }

                // 判断项目维护名称是否已存在，避免重复（排除当前记录）
                var existProjectForm = _projectFormRepository.GetValue(x => x.ProjectName == input.ProjectName && x.Id != input.Id && !x.IsDeleted);
                if (existProjectForm != null)
                {
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Error,
                        Message = "项目表单名称已存在",
                    };
                }

                // 更新基本信息
                projectFormModel = _mapper.Map(input, projectFormModel);
                projectFormModel.UpdatedTime = DateTime.Now;
                var res = _projectFormRepository.Update(projectFormModel);

                // 更新关联关系
                if (input.ProjectMaintenanceIds != null)
                {
                    // 删除旧的关联关系（软删除）
                    var oldRelations = _projectFormMaintenanceRelationRepository.GetAll()
                        .Where(x => x.ProjectFormId == input.Id && !x.IsDeleted)
                        .ToList();

                    foreach (var relation in oldRelations)
                    {
                        relation.IsDeleted = true;
                        relation.UpdatedTime = DateTime.Now;
                        relation.UpdatedBy = projectFormModel.UpdatedBy;
                        _projectFormMaintenanceRelationRepository.Update(relation);
                    }

                    // 添加新的关联关系
                    foreach (var maintenanceId in input.ProjectMaintenanceIds)
                    {
                        // 验证项目维护ID是否存在
                        var maintenance = _projectMaintenanceRepository.GetValue(x => x.Id == maintenanceId && !x.IsDeleted);
                        if (maintenance == null)
                        {
                            continue; // 跳过不存在的项目维护ID
                        }

                        // 创建关联记录
                        var relation = new ProjectFormMaintenanceRelation
                        {
                            Id = YitIdHelper.NextId(),
                            ProjectFormId = input.Id,
                            ProjectMaintenanceId = maintenanceId,
                            CreatedBy = projectFormModel.UpdatedBy,
                            CreatedTime = DateTime.Now
                        };

                        _projectFormMaintenanceRelationRepository.Add(relation);
                    }
                }

                db.Ado.CommitTran();

                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Data = res,
                    Message = "项目表单更新成功"
                };
            }
            catch (Exception ex)
            {
                db.Ado.RollbackTran();

                return new ApiResult<int>
                {
                    Code = ApiEnums.Error,
                    Message = $"更新项目表单失败：{ex.Message}"
                };
            }
        }


        /// <summary>
        /// 删除项目表单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ApiResult<int> DeleteProjectForm(long id)
        {
            var projectFormModel = _projectFormRepository.GetValue(x => x.Id == id);
            if (projectFormModel == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.Error,
                    Message = "项目表单不存在"
                };
            }

            projectFormModel.IsDeleted = true;
            projectFormModel.UpdatedTime = DateTime.Now;

            var res = _projectFormRepository.Update(projectFormModel);

            return new ApiResult<int>
            {
                Code = ApiEnums.Success,
                Data = res,
                Message = "项目表单删除成功"
            };
        }

    }
}
